<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '格知汇GACC',
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <view class="entire">
    <image
      style="z-index: -10; position: fixed; top: 0; width: 100vw; height: 100vh"
      :src="listBg"
      mode="aspectFill"
    ></image>
    <!--上方搜索栏区域-->
    <view class="div1">
      <Backbar title="搜索详情" />
      <view class="title">
        <wht-search v-model="pageData.searchWord" @search="handleSearch" />
      </view>
      <!-- 一级选择器 -->
      <wht-tabs
        v-model="pageData.tab1"
        :list="pageData.tabList1"
        @change="handleTab1"
        bgColor="#e5effd"
        color="#898889"
        active-color="#254872"
        line-color="#254872"
        :font-size="26"
        :min-width="175"
        :padding="100"
      ></wht-tabs>
    </view>
    <!--下方搜索信息区域-->
    <scroll-view
      ref="scrollContainer"
      scroll-y="true"
      class="div2"
      enable-flex="true"
      :style="{ height: pageData.div2Height + 'px' }"
      @scrolltolower="handleScroll"
    >
      <!-- 空显示 -->
      <view
        v-if="
          (pageData.tab1 === 0 && pageData.courseList.length === 0) ||
          (pageData.tab1 === 1 && pageData.knowledgeList.length === 0)
        "
        style="
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
        "
      >
        <image src="/static/images/icons/imgNone.png" style="width: 309rpx; height: 259rpx"></image>
      </view>

      <!--课程列表-->
      <view v-if="pageData.tab1 === 0">
        <view
          v-for="(item, index) in pageData.courseList"
          :key="index"
          @click="navToCourseInfo(item)"
        >
          <TiniCourseItem :course="item" />
        </view>
      </view>

      <!--知识列表-->
      <view v-if="pageData.tab1 === 1">
        <view
          v-for="(item, index) in pageData.knowledgeList"
          :key="index"
          @click="navToRichText(item)"
        >
          <KnowledgeItem :knowledge="item" />
        </view>
      </view>

      <!--加载中，到底啦横幅-->
      <view
        style="margin-top: 30rpx; padding-bottom: 50rpx"
        v-if="
          !(
            (pageData.tab1 === 0 && pageData.courseList.length === 0) ||
            (pageData.tab1 === 1 && pageData.knowledgeList.length === 0)
          )
        "
      >
        <wd-divider color="black">{{ pageData.loading ? '加载中...' : '已经到底了' }}</wd-divider>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { reactive, onMounted, ref, nextTick } from 'vue'
import { searchList } from '@/service/search/search'
import CourseItem from '@/components/CourseItem/CourseItem.vue'
import KnowledgeItem from '@/components/KnowledgeItem/KnowledgeItem.vue'
import TiniCourseItem from '@/components/CourseItem/TiniCourseItem.vue'
import { listBg } from '@/static/imgMap'

const pageData = reactive({
  tab1: 0,
  tabList1: ['课程', '知识'],
  div2Height: 0,
  searchWord: '',
  courseList: [],
  knowledgeList: [],
  page: 1,
  limit: 10,
  totalCount: 0,
  loading: false, // 标记是否正在加载数据
})

// 搜索函数，用于初次加载数据
const handleSearch = async () => {
  pageData.page = 1
  if (pageData.tab1 === 0) {
    pageData.courseList = []
  } else {
    pageData.knowledgeList = []
  }
  pageData.totalCount = 0

  const params = {
    Keyword: pageData.searchWord,
    Type: pageData.tab1 === 0 ? [0] : [11],
    page: pageData.page,
    limit: pageData.limit,
  }

  await fetchData(params)
}

// 加载更多数据
const loadMoreData = async () => {
  if (
    pageData.loading ||
    pageData.totalCount <=
      (pageData.tab1 === 0 ? pageData.courseList.length : pageData.knowledgeList.length)
  ) {
    return
  }

  pageData.loading = true

  const params = {
    Keyword: pageData.searchWord,
    Type: pageData.tab1 === 0 ? [0] : [11],
    page: pageData.page,
    limit: pageData.limit,
  }

  try {
    await fetchData(params)
  } catch (error) {
    console.error('Error loading more data:', error)
  } finally {
    pageData.loading = false
  }
}

// 实际发起网络请求的函数
const fetchData = async (params) => {
  try {
    const res = await searchList(params)

    if (pageData.tab1 === 0) {
      if (pageData.page === 1) {
        pageData.courseList = res.data.items
      } else {
        pageData.courseList.push(...res.data.items)
      }
    } else {
      if (pageData.page === 1) {
        pageData.knowledgeList = res.data.items
      } else {
        pageData.knowledgeList.push(...res.data.items)
      }
    }
    pageData.totalCount = res.data.totalCount
    pageData.page += 1
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}

const handleTab1 = (index) => {
  console.log(index)
  handleSearch() // 切换标签时重新搜索
}

const navToCourseInfo = (item) => {
  uni.navigateTo({
    url: '/pages/courseCenter/CourseInfo/CourseInfo',
  })
}

const navToRichText = (data) => {
  uni.navigateTo({
    url:
      '/pages-sub/knowledgeRichText/knowledgeRichText?data=' +
      encodeURIComponent(JSON.stringify(data)),
  })
}

const handleScroll = () => {
  console.log('Scroll event triggered') // 调试信息
  if (!pageData.loading) {
    console.log('Loading more data...')
    loadMoreData()
  }
}

onMounted(() => {
  // 自适应滑动列表长度
  uni.getSystemInfo({
    success(res) {
      const screenHeight = res.windowHeight
      uni
        .createSelectorQuery()
        .select('.div1')
        .boundingClientRect((data) => {
          pageData.div2Height = screenHeight - data.height
        })
        .exec()
    },
  })
  // 初始加载数据
  handleSearch()
})
</script>

<style scoped lang="scss">
.entire {
  width: 100%;
  .div1 {
    background-color: rgb(37, 73, 115);
    .title {
      background: rgb(37, 73, 115);
      width: 750rpx;
      height: 120rpx;
    }
  }
  .div2 {
    display: flex;
    flex-direction: column;
    width: 100%;
    overflow-y: auto; /* 使用 auto 确保只有在需要时才显示滚动条 */
    max-height: 100vh; /* 确保最大高度为视口高度 */
  }
}
</style>
